﻿using System;
using System.Reactive.Concurrency;
using System.Reactive.Subjects;
using Sbcx.ComponentModel;

namespace Sbcx {

    public static class ConnectedObservableExtensions {

        /// <summary>Returns an observable sequence that forces a connection as when a connection is requested.</summary>
        /// <param name="connectableObservable">a delegate that produces a connected observable</param>
        /// <param name="retryInterval">null to retry immediately, or a timespan to attempt retry</param>
        /// <remarks>This sequence never terminates, and all exceptions are routed to the exception stream.</remarks>
        public static IPersistedConnectableObservable<T> Persist<T> (
            this Func<IConnectableObservable<T>> connectableObservable,
            TimeSpan? retryInterval) {

            return Persist (connectableObservable, retryInterval, Scheduler.ThreadPool);
        }

        /// <summary>Returns an observable sequence that forces a connection as when a connection is requested.</summary>
        /// <param name="connectableObservable">a delegate that produces a connected observable</param>
        /// <param name="retryInterval">null to retry immediately, or a timespan to attempt retry</param>
        /// <remarks>This sequence never terminates, and all exceptions are routed to the exception stream.</remarks>
        public static IPersistedConnectableObservable<T> Persist<T> (
            this Func<IConnectableObservable<T>> connectableObservable,
            TimeSpan? retryInterval,
            IScheduler scheduler) {

            if (connectableObservable == null)
                throw new ArgumentNullException ("connectableObservable", "connectableObservable is null.");
            if (scheduler == null)
                throw new ArgumentNullException ("scheduler", "scheduler is null.");

            return new PersistedConnectableObservable<T> (connectableObservable, retryInterval, scheduler);
        }
    }
}